package br.com.imagechess.player;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class ChessGameDrawer {
	
	private static Graphics table;
	
	Color blackPieces = new Color(210, 210, 210);
	Color whitePieces = new Color(255, 255, 255);
	Color whiteSquares = new Color(100, 100, 100);
	Color blackSquares = new Color(50, 50, 50);
	
	private Map<String, Graphics> gameTable = new HashMap<String, Graphics>();
	private BufferedImage tableImage;
	private ImageLoader imageLoader = new ImageLoader();
	private static String IMG_DIR = "images/";
	
	private int step = 50;

	
	public ChessGameDrawer(int size) {
		step = size / 8;
		tableImage = new BufferedImage(size, size, 1);
	}

	public void print() {
		JPEGImageEncoder ImgEnc;
		try {
			ImgEnc = JPEGCodec.createJPEGEncoder(new FileOutputStream("ChessGame.jpg"));
			ImgEnc.encode(tableImage);
			ImgEnc.getOutputStream().close();
			System.out.println("over");
		} catch (Exception e) {
			//e.printStackTrace();
		}
	}
	
	public void print(OutputStream o) {
		JPEGImageEncoder ImgEnc;
		try {
			ImgEnc = JPEGCodec.createJPEGEncoder(o);
			ImgEnc.encode(tableImage);
			ImgEnc.getOutputStream().close();
			System.out.println("over");
		} catch (Exception e) {
			//e.printStackTrace();
		}
	}

	private void draw(Piece piece, int x, int y, int w, int h, boolean inWhite) {
		Graphics2D p = (Graphics2D) tableImage.getGraphics();
		p.drawRect(x, y, w, h);
		
		String imageName = "";
		String bkg = "_b";
		if(inWhite) bkg = "_w";
		
		if(piece == null) {
			imageName = IMG_DIR + "VOID" + bkg + ".jpg";
		} else {
			imageName = IMG_DIR + piece.getName() + (piece.isWhite()? "_w" : "_b") + bkg + ".jpg";
		}
		
		System.out.println(imageName + "; x: " + x + ", y:" + y);
		
		Image i = imageLoader.loadImage(imageName);
		
		if(i != null) p.drawImage(i, x, y, w, h, null);
	}
	
	public void draw(ChessGame game) {
		String[] w = new String[]{"A","B","C","D","E","F","G","H"};
		String[] h = new String[]{"1","2","3","4","5","6","7","8"};
		Map<String, Piece> gameTable = game.getGameTable();
		
		int x = 0;
		int cw = 0;
		
		for (String sw : w) {
			int y = 0;
			int ch = cw%2>0?0:1;
			for (String sh : h) {
				String k = sw + sh;
				Piece piece = gameTable.get(k);
				draw(piece, x, y, step, step, ch%2>0?true:false);
				y += step;
				ch++;
			}
			x += step;
			cw++;
		}
	}
}
